<?php
/**
 * 地区model
 * 
 */
namespace app\stream\model;
class Video extends \think\Model {
    protected $tableName = 'video';
    protected $fields = [
        'vid',
        'uid',
        'video_start',
        'video_end',
        'video_ext',
        'video_path',
        'create_time',
        'save_time',
        'persistentId',
        'status',
        'video_title',
        'video_icon',
        'from_stream',
        'video_location',
        'replay_count',
	'diggs'
    ];
    protected $auto = ['create_time' => NOW_TIME];
    
    /**
     * @name 添加数据
     */
    public function addVideo($data){
        $data = self::validateData($data,true);
        if(!empty($data)){
            return parent::add($data);
        }
        return false;
    }
    
     /**
     * @name 本地数据验证(过滤和自动填充数据)
     * @author martinsun syh@sunyonghong.com
     * @access protected
     * @param array $data 验证的数据数组
     * @param boolean $auto 是否自动填充数据
     * @return array 验证后的数据
     */
    protected function validateData($data = [] , $auto = false){
        if(!$data || !is_array($data)) return false;
        $res = [];
        $this->fields = $this->fields ?: $this->getFields();
        foreach ($data as $k=>$v){
            in_array($k,$this->fields) && $res[$k] = $v;
        }
        if($auto && !empty($this->auto)){
            return array_merge($res,$this->auto);
        }
        return $res;
    }
    
    /**
     * @name 检测某数据是否存在
     */
    public function hasOne($map =[]){
        if(!empty($map)){
            return $this->where($map)->count() > 0 ? true : false;
        }
        return false;
    }
    
    /**
     * @name 更新数据
     */
    public function update($data = [],$where = []){
        if(empty($data)||empty($where)) return false;
        return (boolean)$this->where($where)->save($data);
    }
    
    /**
     * @name 取得列表数据
     */
    public function getList($map = [] ,$fields = [],$format = true,$limit = 10,$order = ''){
        $list = [];
        $fields = empty($fields) ? $this->fields : (is_array($fields) ? $fields:explode(',',$fields)) ;
        $order = $order ?:'vid desc';
        if(isset($map['sex'])){
            $subsql = M('user')->where(['uid'=>$map['uid'],'sex'=>$map['sex']])->field('uid')->limit($limit)->buildSql();
            unset($map['sex'],$map['uid']);
            $list =$this->alias('video')->join($subsql. ' user', 'user.uid = video.uid')->where($map)->order($order)->findPage($limit);
        }else{
            $list = $this->where($map)->order($order)->findPage($limit);
        }
        if($list['data']){
            //改变原数据
            $data = $list['data'];
            $list['data'] = [];
            //取得前缀
            $video_prefix = model('admin/Config')->getConfigValue(['type'=>'video','key'=>'video_config'],'video_prefix');
            $video_prefix = $video_prefix ? $video_prefix : 'video_';
            foreach($data as &$v){
		$v['source_id'] = (int)$v['vid'];
                $v['vid'] = encrypt_id($v['vid']);
                $v['video_title'] && $v['video_title'] = formatEmoji($v['video_title'],false);
                $uid = $v['uid'];
                $v['status_code'] = $v['status'];
                //数据格式化
                if($format === true){
                    $v['create_time_format'] = $v['create_time'] ? date('Y-m-d H:i:s',$v['create_time']) : '';
                    $v['save_time_format'] = $v['save_time'] ? date('Y-m-d H:i:s',$v['save_time']) : '';
                    $v['video_start_format'] = $v['video_start'] ? date('Y-m-d H:i:s',$v['video_start']) : '';
                    $v['video_end_format'] = $v['video_end'] ? date('Y-m-d H:i:s',$v['video_end']) : '';
                    $v['replay_count_format'] ? (int)$v['replay_count'] : 0;
                    switch ($v['status']){
                        case '0':
                            $v['status'] = '处理完成';
                            break;
                        case '1':
                            $v['status'] = '等待处理';
                            break;
                        case '2':
                            $v['status'] = '正在处理';
                            break;
                        case '3':
                            $v['status'] = '处理失败';
                            break;
                        case '5':
                            $v['status'] = '资源服务器已废弃';
                            break;
                        default:
                            $v['status'] = '等待处理';
                            break;
                    }
                }
                //开始命名
                $name = $v['video_start'].$v['video_end'].$v['uid'];//名字主体
                //生成视频保存的名字
                $name = $video_prefix.md5($name).'.'.$v['video_ext'];//最终的视频名称
                $v['video_playurl'] = "http://".self::getTsByStreamId($v['from_stream']).'/'. $v['video_path'];//.'/'.$v['from_stream'].'/'.$name
                if(!is_numeric($v['video_icon'])){
                    $v['video_icon'] = (object)[C('qiniu.cdn-url'). '/' .$v['video_icon']];
                }else{
                    $v['video_icon']    = (object)model('attach/Attach',['getAttachUrl',$v['video_icon']]);
                }
                //如果指定了字段
                if($format !== true){
                    foreach($fields as $value){
                        $item['video'][$value] = $v[$value];
                    }
                }else{
                    $item['video'] = $v;
                }
                $item['video']['status_code'] = $v['status_code'];
                $item['video']['time'] = $v['video_end']-$v['video_start'];
                $item['video']['time_info'] = getTimediff($v['video_start'],$v['video_end']);
		$item['video']['source_id'] = $v['source_id'];
                $item['user'] = self::getUserData($uid);
                //uname替换
                if(!$v['video_title']){
                    $video_title_config = model('admin/Config')->getConfigValue(['type'=>'video','key'=>'video_config'],'video_title') ?: '[uname]的视频';
                    $item['video']['video_title'] = str_replace('[uname]',model('open/User')->getUsername($uid),$video_title_config);
                }
                unset($v);
                array_push($list['data'],$item);
            }
            unset($data);
        }
        return $list;
    }
    /**
     * 取得单条数据信息
     */
    public function getOne($map){
        $one = [];
        if($map){
            $one = $this->where($map)->find();
        }
        
        if($one){
            //取得前缀
            $video_prefix = model('admin/Config')->getConfigValue(['type'=>'video','key'=>'video_config'],'video_prefix');
            $video_prefix = $video_prefix ? $video_prefix : 'video_';
            //开始命名
            $name = $one['video_start'].$one['video_end'].$one['uid'];//名字主体
            //生成视频保存的名字
            $name = $video_prefix.md5($name).'.'.$one['video_ext'];//最终的视频名称
            //$one['video_playurl'] = self::getTsByStreamId($one['from_stream']).'/'. $one['video_path'].'/'.$one['from_stream'].'/'.$name;
	        $one['video_playurl'] = C('qiniu.cdn-url') . '/' . $one['video_path'];
        }
        return $one;
    }
    /**
     * @name 通过视频所在的应用获取切片域名
     */
    protected function getTsByStreamId($stream_id = ''){
        if(!$stream_id) return '';
        //目前仅支持一个
        return model('admin/Config')->getConfigValue(['type'=>'stream','key'=>'stream_service'],'hub_ts_url');
        /**匹配hub
        $reg = '/(?<=\.)[^\.]+/';
        preg_match($reg,$stream_id,$res);
        $config_hub = C('qiniu_hub');
        foreach($config_hub as $v){
            if($v['hub_name'] == $res[0]) return $v['hub_ts_url'];
        }
        return '';
        **/
    }
    /**
     * @name 获取主播信息
     */
    public function getUserData($uid = 0){
        return ['usid' => model('open/User')->getUsidByUid($uid)];
    }
    /**
     * 获取回放列表
     */
    public function getPlayBackList($map = [],$limit = 10,$order = 'vid desc',$is_admin = false){
        $field = ['vid','video_title','video_start','video_end','video_icon','video_location','replay_count','video_ext', 'diggs'];
        if($map['uid'] == '0') unset($map['uid']);
        //模糊查询用户
        $map['is_del'] = $is_admin ? ['neq', 1] : 0;
        if($map['video_title']){
            $uids = M('user')->where(['uname'=>$map['video_title']])->field('uid')->limit(10)->select();
            $uids = getSubByKey($uids,'uid');
            $key = array_search($map['uid'][1], $uids);
            if ($key !== false){
                array_splice($uids, $key, 1);
            }
            
            if(!empty($uids)){
                //$map1['uid'] = array('in',$uids);
                //$map1['video_title'] = '';
                //$map1['_logic'] = 'and';
                //$map2['_complex'] = $map1;
                //$map2['video_title'] = $map['video_title'];
                //$map2['_logic'] = 'or';
                //$where['_complex'] = $map2;
                $where = "`uid` IN (".implode(',',$uids).") AND (`video_title` = '' OR `video_title` LIKE '".$map['video_title'][1]."')";
                unset($map['video_title']);
                
            }else{
                $where = "`video_title` LIKE '".$map['video_title'][1]."'";
            }
            //$where = array_merge($where,$map);
            if($map['video_location']){
                $where .= " AND `video_location` LIKE '".$map['video_location'][1]."'";
            }
            $where .= $is_admin ? (' AND `is_del` != 1 ') : (' AND `is_del` =0 ');
            if(is_array($map['status'])){
                $where .= ' AND `status` '.implode(' ',$map['status']);
            }elseif(isset($map['status'])){
                $where .= ' AND `status` = '.(int)$map['status'];
            }
        }else{
            $where = $map;
        }
	$list = $this->getList($where,$field,$is_admin,$limit,$order);
        // echo $this->getLastSql();exit;
        if($is_admin){
            return object2array($list);
        }
        if($list['gtLastPage'] || !$list['data']){
            return [];
        }

        return $list['data'];
    }
    /**
     * 获取指定用户所关注的用户
     */
    public function getFollowByUid($uid = 0){
        if(!$uid) return [];
        $uids = D('user/UserFollow')->getFollowListByUid($uid);
        if(!$uids){
            return ['code'=>'00000','data'=>[],'message'=>'还没有关注别人喔~'];
        }
        return $uids;
    }
    /**
     * 获取单个视频的播放地址
     */
    public function getPlayUrl($vid = 0){
        if(!$vid) return false;
        $url = self::getOne('vid='.$vid)['video_playurl'];
        if($url){
            self::addPlayCount($vid);
            return $url;
        }
        return '';
    }
    /**
     * @name 添加播放次数
     */
    public function addPlayCount($vid = 0){
        if(!$vid) return false;
        return $this->where('vid='.$vid)->setInc('replay_count');
    }
    /**
     * @name 检测本地的视频数据保存状态
     * @access public
     * @description 当用户的直播状态由在直播->停止直播时,会回调保存本次的直播视频
     * @param array $map 本地的数据信息
     * @return boolean 如果本地存在数据返回true
     */
    public function checksaveStream($map = []){
        unset($map['video_end']);
        return $this->hasOne($map);
    }
}
